
const findEle = (parent, type) => {
  return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
}

function dispatchEvent(el, type) {
  const evt = document.createEvent('HTMLEvents')
  evt.initEvent(type, true, true)
  el.dispatchEvent(evt)
}
const FilterCharacter = {
  inserted: el => {
    const inputEle = findEle(el, 'input')
    // const regRule1 = /[`~,.<>;':"\/\[\]\|{}()-=_+]/g
    const regRule2 = /[~%&<>\\[\]\{\}=_+]/g
    const handler = function(event) {
      const newVal = event.target.value.replace(regRule2, '')
      if (event.target.value !== newVal) {
        event.target.value = newVal
        dispatchEvent(inputEle, 'input')
      }
    }
    el.inputEle = inputEle
    el._blurHandler = handler
    inputEle.addEventListener('keyup', handler)
  },
  unbind(el) {
    const { inputEle } = el
    inputEle.removeEventListener('keyup', el._blurHandler)
  }
}
FilterCharacter.install = function(Vue) {
  Vue.directive('FilterCharacter', FilterCharacter)
}

export default FilterCharacter
